﻿using System.Linq;
using System.Web.Mvc;

namespace Zavand.Web.Mvc.Manana.Framework
{
    public class BaseController : Controller
    {
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            
            // Remove optional params
            if (requestContext != null)
            {
                var httpContext = requestContext.HttpContext;
                if (httpContext != null && httpContext.CurrentHandler is MvcHandler)
                {
                    var rvd = requestContext.RouteData.Values;
                    var matchingKeys = (from entry in rvd
                                        where entry.Value == BaseUrlParameter.Optional
                                        select entry.Key).ToArray();
                    foreach (var key in matchingKeys)
                    {
                        rvd.Remove(key);
                    }
                }
            }
        }

        public TModel GetModel<TModel, TRoute, TController>(TRoute r, TController c)
            where TModel : BaseModel<TRoute, TController>, new()
            where TRoute : BaseRoute
            where TController : BaseController
        {
            var m = new TModel();
            m.SetupModel(c, r);
            return m;
        }

        public void SetupModel<TModel, TRoute, TController>(TModel m, TRoute r, TController c)
            where TModel : BaseModel<TRoute, TController>, new()
            where TRoute : BaseRoute
            where TController : BaseController
        {
            m.SetupModel(c,r);
        }

        public ActionResult RedirectToAction<TRoute>()
            where TRoute : BaseRoute, new()
        {
            var r = new TRoute();
            return RedirectToAction(null, r);
        }

        public ActionResult RedirectToAction(BaseRoute currentRoute, BaseRoute r)
        {
            return Redirect(Url.RouteUrl(currentRoute, r));
        }
    }

    /// <summary>
    ///     This class is needed to fix routing issue described at the page below:
    ///     http://weblogs.asp.net/imranbaloch/archive/2010/12/26/routing-issue-in-asp-net-mvc-3-rc-2.aspx
    /// </summary>
    public class BaseUrlParameter
    {
        public static readonly BaseUrlParameter Optional = new BaseUrlParameter();
    }
}